﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using l1cs.server.model;
using MySql.Data.MySqlClient;
using System.Data;
using l1cs.server.utils;

namespace l1cs.server.datatables
{
    class PolyTable
    {
        private static Logger _log = Logger.getLogger( typeof( PolyTable ).FullName );

        private static PolyTable _instance;

        private Dictionary<String, L1PolyMorph> _polymorphs = new Dictionary<String, L1PolyMorph>();

        private Dictionary<int, L1PolyMorph> _polyIdIndex = new Dictionary<int, L1PolyMorph>();

        public static PolyTable getInstance()
        {
            if ( _instance == null )
            {
                _instance = new PolyTable();
            }
            return _instance;
        }

        private PolyTable()
        {/*TTOK*/
            String sqlstr = "SELECT * FROM polymorphs";
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                foreach ( DataRow item in wrapper.GetDataTable(sqlstr).Rows )
                {
                    int id = SqlUtils.toInt( item["id"] );
                    String name = Convert.ToString( item["name"] );
                    int polyId = SqlUtils.toInt( item["polyid"] );
                    int minLevel = SqlUtils.toInt( item["minlevel"] );
                    int weaponEquipFlg = SqlUtils.toInt( item["weaponequip"] );
                    int armorEquipFlg = SqlUtils.toInt( item["armorequip"] );
                    bool canUseSkill = Convert.ToBoolean( item["isSkillUse"] );
                    int causeFlg = SqlUtils.toInt( item["cause"] );

                    L1PolyMorph poly = new L1PolyMorph( id, name, polyId, minLevel, 
                                        weaponEquipFlg, armorEquipFlg, canUseSkill, causeFlg );

                    _polymorphs[name] = poly;
                    _polyIdIndex[polyId] = poly;
                }
            }
            _log.config( "変身リスト " + _polymorphs.Count + "件ロード" );
        }

        /// <summary>
        /// 変身名からL1PolyMorphを返す。
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public L1PolyMorph getTemplate( String name )
        {/*TTOK*/
            L1PolyMorph ret = null;
            _polymorphs.TryGetValue( name, out ret );
            return ret;
        }

        /// <summary>
        /// 変身IDからL1PolyMorthを返す。
        /// </summary>
        /// <param name="polyId"></param>
        /// <returns></returns>
        public L1PolyMorph getTemplate( int polyId )
        {/*TTOK*/
            L1PolyMorph ret = null;
            _polyIdIndex.TryGetValue( polyId, out ret );
            return ret;
        }
    }
}
